//
//  LGTTaskVC.swift
//  KJLGT
//
//  Created by jenkin on 2019/8/7.
//  Copyright © 2019年 jenkin. All rights reserved.
//

import UIKit
import ZHRefresh


class LGTTaskVC: LGTBaseVC, UIScrollViewDelegate{
   
    var mainView:UIScrollView?
    var topView:UIView?
    var postParamModel:PostParamModel?
    var bigTypeList:Array<LGTButton> = []  //大类型选择
    var smallTypeList:Array<LGTButton> = [] //小类型选择
    var vcArray:Array<LGTTaskListVC> = []
    var currentVC:LGTTaskListVC?
    var bigType:Int = 0 //大类型
    var smallType:Int = 0 //小类型
    var openSelectBlock:ClickIndexWithIndexBlock? //类型选择视图点击
    var typeSelectBlock:ClickIndexBlock? //类型选择回掉
    var typeIndex:Int = -1
    var selectListView:LGTTaskTypeSelectView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setBlock()
        self.getParam()
        
        NotificationCenter.default.addObserver(self, selector: #selector(viewChangeState), name: LLZ_TaskChange_Note, object: nil)
    }
    
    //视图更改
    @objc func viewChangeState(note:Notification){
        let type:Int = note.userInfo?["type"] as? Int ?? 0
        if type == LLZTaskHeadClickType.SimpleType.rawValue{
            self.bigTypeSelect(sender: self.bigTypeList[2])
        }else if type == LLZTaskHeadClickType.HighType.rawValue{
            self.bigTypeSelect(sender: self.bigTypeList[1])
        }else if type == LLZTaskHeadClickType.MoreType.rawValue{
            self.bigTypeSelect(sender: self.bigTypeList[0])
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: LLZ_TaskChange_Note, object: nil)
    }
    
    func setBlock(){
        weak var weakSelf = self
        self.reloadBlock = {() in
            weakSelf?.getParam()
        }
        
        //打开
        self.openSelectBlock = { (tag:Int, index:Int) in
            let taskTypeSelctVC:LGTTaskTypeSelectVC = LGTTaskTypeSelectVC()
            taskTypeSelctVC.modalPresentationStyle = .overCurrentContext
            var index = weakSelf?.typeIndex ?? -1
            if index == -1{
                index = 0
            }
            taskTypeSelctVC.currentIndex = index
            taskTypeSelctVC.typeSelectBlock = weakSelf?.typeSelectBlock
            taskTypeSelctVC.type_list = weakSelf?.postParamModel?.type_list ?? []
            weakSelf?.tabBarController?.present(taskTypeSelctVC, animated: false, completion: nil)
        }
    
        //类型选择
        self.typeSelectBlock = {(index:Int) in
            weakSelf?.typeIndex = index
            if index == -1{
                weakSelf?.selectListView?.setTitle(title: "类型")
            }else{
                let model:PostNameModel? = weakSelf?.postParamModel?.type_list?[index]
                if model != nil{
                     weakSelf?.selectListView?.setTitle(title: model?.name ?? "")
                }
            }
            
            weakSelf?.currentVC?.param = weakSelf?.getTaskParam() ?? [:]
        }
    }
    
    override func setUI() {
        super.setUI()
        self.setBavBarStyle(navBarHiden: true, title: "", back: false)
        self.topView = UIView.init()
        let topH:Double = NavBarH() + 45.0
        self.view.addSubview(self.topView!)
        self.topView?.backgroundColor = UIColor.white
        self.topView!.snp.makeConstraints { (make) in
            make.top.left.right.equalTo(0)
            make.height.equalTo(topH)
        }
        
        let line:UIImageView = LGTViewCreateUtil.share.createLineView()
        self.topView?.addSubview(line)
        line.snp.makeConstraints { (make) in
            make.height.equalTo(1)
            make.top.equalTo(NavBarH())
            make.left.right.equalTo(0)
        }
        
        //大类型选择
        let topSelecView:UIImageView = LGTViewCreateUtil.share.createImageViewCorner(corner: 15.0)
        self.topView?.addSubview(topSelecView)
        topSelecView.isUserInteractionEnabled = true
        topSelecView.backgroundColor = ViewBackColor
        topSelecView.snp.makeConstraints { (make) in
            make.height.equalTo(30)
            make.centerX.equalToSuperview()
            make.bottom.equalTo(line).offset(-8)
            make.width.equalTo(180)
        }
        
        //数据视图
        let mainH:Double = Double(KScreenH) - topH - TabBarH()
        self.mainView = UIScrollView.init(frame: CGRect.init(x: 0, y: topH, width: Double(KScreenW), height: mainH))
        self.mainView?.backgroundColor = ViewBackColor
        self.view.addSubview(self.mainView!)
        self.mainView?.contentSize = CGSize.init(width: KScreenW * 3, height: 0)
        self.mainView?.isPagingEnabled = true
        self.mainView?.delegate = self
        self.mainView?.isScrollEnabled = true
        self.mainView?.showsHorizontalScrollIndicator = false
        
        //大类型
        let dataArray:Array<String> = ["全部", "高价", "简单"]
        //let dataArray:Array<String> = ["全部", "高价"]
        for i in 0..<dataArray.count{
            let title:String = dataArray[i]
            let btn = LGTViewCreateUtil.share.createTextLGTButton(title: title, font: KFont(size: 15.0), color: TextColor, selectedColor: UIColor.white, dH:5.0, corner:15.0)
            btn.backgroundColor = ViewBackColor
            topSelecView.addSubview(btn)
            btn.snp.makeConstraints { (make) in
                make.left.equalTo(i * 60)
                make.height.equalTo(30)
                make.top.equalTo(0)
                make.width.equalTo(60)
            }
            btn.tag = i
            self.bigTypeList.append(btn)
            btn.addTarget(self, action: #selector(bigTypeSelect), for: UIControl.Event.touchUpInside)
            if i == 0{
                btn.isSelected = true
            }
            
            let vc:LGTTaskListVC = LGTTaskListVC()
            vc.nav = self.navigationController
            vc.view.frame = CGRect.init(x: Double(i) * Double(KScreenW), y: 0, width: Double(KScreenW), height: mainH)
            vc.view.backgroundColor = YellowColor
            self.vcArray.append(vc)
        }
        
        let line2:UIImageView = LGTViewCreateUtil.share.createLineView()
        self.topView?.addSubview(line2)
        line2.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(0)
            make.height.equalTo(1)
        }
    }
    
    func getParam(){
        //获取类型
        self.showLoading(loadingType: .TabbarLoadingType)
        weak var weakSelf = self
        LGTHttpUtil.httpUtil.requestData(url: LLZ_Task_Type_URL, param: [:], success: { (json) in
            let data:Dictionary<String, Any> = ["type_list": json["data"] as? Array<Any> ?? []]
            weakSelf?.postParamModel = try! lgtDecode(PostParamModel.self, param: (data))
            weakSelf?.initTypeSelect()
            weakSelf?.closeLoading()
        }) { (json) in
            weakSelf?.showNoData(image: Net_NoData_Image, text: Net_Error_Text, subText: Net_Reload_Text, haveNav:false)
        }
    }
    
    //类型初始化
    func initTypeSelect(){
        //let count:Int = self.postParamModel?.type_list?.count ?? 0
        var conditionListModel:ConditionListModel = ConditionListModel()
        conditionListModel.title = "类型"
        conditionListModel.list = self.postParamModel?.type_list ?? []
        self.selectListView = LGTTaskTypeSelectView.initWithPosition(positon: LGTTaskTypeSelectView.Position.Left, conditionListModel: conditionListModel, index: 0)
        self.topView?.addSubview(self.selectListView!)
        self.selectListView?.clickBlock = self.openSelectBlock
        self.selectListView!.snp.makeConstraints { (make) in
            make.height.equalTo(45)
            make.bottom.equalTo(0)
            make.left.equalTo(0)
            make.width.equalTo(100)
        }
        
        //大类型选择
        let topSelecView:UIImageView = LGTViewCreateUtil.share.createImageViewCorner(corner: 15.0)
        self.topView?.addSubview(topSelecView)
        topSelecView.isUserInteractionEnabled = true
        topSelecView.backgroundColor = UIColor.clear
        topSelecView.snp.makeConstraints { (make) in
            make.height.equalTo(45)
            make.centerX.equalToSuperview()
            make.bottom.equalTo(0)
            make.width.equalTo(180)
        }
        
        let otherSelectTypes:Array<String> = ["默认", "最新", "价格"]
        for i in 0..<otherSelectTypes.count{
            let type:String = otherSelectTypes[i]
            let btn = LGTViewCreateUtil.share.createTextLGTButton(title: type, font: KFont(size: 15.0), color: TextColor, selectedColor: YellowColor, dH:5.0, corner:15.0)
            topSelecView.addSubview(btn)
            btn.tag = i
            self.smallTypeList.append(btn)
            btn.addTarget(self, action: #selector(smallTypeSelect), for: UIControl.Event.touchUpInside)
            btn.snp.makeConstraints { (make) in
                make.left.equalTo(i * 60)
                make.height.equalTo(30)
                make.centerY.equalTo(self.selectListView!)
                make.width.equalTo(60)
            }
            
            if i == 0{
                btn.isSelected = true
            }
        }
        
        //数据初始化
        self.bigTypeSelect(sender: self.bigTypeList[0])
    }
    
    //大类型选择
    @objc func bigTypeSelect(sender:UIButton){
        let index = sender.tag
        self.bigType = index
        for i in 0..<self.bigTypeList.count{
            let button = self.bigTypeList[i]
            button.backgroundColor = ViewBackColor
            button.isSelected = false
            if button.tag == index{
                button.isSelected = true
                button.backgroundColor = YellowColor
            }
        }
        
        
        let currentVC = self.vcArray[index]
        if currentVC == self.currentVC{
            return
        }
        
        self.mainView?.contentOffset = CGPoint.init(x: self.view.frame.size.width * CGFloat(index), y: 0)
        if self.currentVC == nil{
            self.currentVC = currentVC
            self.addChild(self.currentVC!)
            self.currentVC!.beginAppearanceTransition(true, animated: false)
            self.mainView?.addSubview(self.currentVC!.view)
            self.currentVC!.willMove(toParent: self)
            self.currentVC?.param = self.getTaskParam()
        }else{
            self.addChild(currentVC)
            weak var weakSelf = self
            self.transition(from: self.currentVC!, to: currentVC, duration: 0, options: UIView.AnimationOptions.transitionCrossDissolve, animations: {
                
            }) { (finish) in
                if finish == true{
                    currentVC.didMove(toParent: self)
                    weakSelf?.mainView?.addSubview(currentVC.view)
                    weakSelf?.currentVC?.willMove(toParent: nil)
                    weakSelf?.currentVC?.view.removeFromSuperview()
                    weakSelf?.currentVC?.removeFromParent()
                    weakSelf?.currentVC = currentVC
                }else{
                    weakSelf?.currentVC = currentVC
                }
                
                weakSelf?.currentVC?.param = self.getTaskParam()
            }
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let index = Int(scrollView.contentOffset.x / self.view.frame.size.width)
        self.bigTypeSelect(sender: self.bigTypeList[index])
    }
    
    //小类型选择
    @objc func smallTypeSelect(sender:UIButton){
        let index = sender.tag
        self.smallType = index
        for i in 0..<self.smallTypeList.count{
            let button = self.smallTypeList[i]
            button.isSelected = false
            if button.tag == index{
                button.isSelected = true
            }
        }
        self.currentVC?.param = self.getTaskParam()
    }
    
    //获取参数
    func getTaskParam() -> Dictionary<String, Any>{
        var param:Dictionary<String, Any> = [:]
        //大类型选择
        var BigTypeKey = ["", "is_high_price", "is_simple"]
        let key:String = BigTypeKey[self.bigType]
        if key.count != 0{
            param[key] = 1
        }
        
        //小排序
        var smallTypeKey = ["", "order", "order"]
        let smallKey:String = smallTypeKey[self.smallType]
        if smallKey.count != 0{
            param[smallKey] = self.smallType
        }

        //类型选择
        if self.typeIndex != -1{
            let model:PostNameModel? = self.postParamModel?.type_list?[self.typeIndex]
            if model != nil{
                param["type"] = model?.value ?? ""
            }
        }
        
        return param
    }
}



/**
class LGTTaskVC: LGTBaseVC, UITableViewDelegate, UITableViewDataSource, LGTTaskConditionAlertDelegate{
    var taskConditionModel:TaskConditionModel?
    var selectArray:Array<LGTTaskTypeSelectView> = []
    var selectBlock:ClickIndexWithIndexBlock?
    var tableView:UITableView?
    var data:Array<TaskModel> = []
    var page:Int = 1
    var selectIndex:Int = -1
    lazy var conditionAlertVC:LGTTaskConditionAlertVC = {
        let vc:LGTTaskConditionAlertVC = LGTTaskConditionAlertVC()
        // vc.view.addSubview(weakSelf?.navBar)
        vc.modalPresentationStyle = .overCurrentContext
        vc.delegate = self
       return vc
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setBlock()
        self.getTaskCondition()
        self.tableView?.header?.beginRefreshing()
    }
    
    func setBlock(){
        weak var weakSelf = self
        
        self.reloadBlock = {() in
            if weakSelf?.taskConditionModel == nil{
                weakSelf?.getTaskCondition()
            }
            
            if weakSelf?.data.count == 0{
                weakSelf?.tableView?.header?.beginRefreshing()
            }
        }
        
        //类型选择
        self.selectBlock = {(tag:Int, index:Int) in
            if self.selectIndex == tag{
                weakSelf?.conditionAlertVC.dismissVC()
                self.selectIndex = -1
                return
            }
            
            self.selectIndex = tag
            let count:Int = weakSelf?.selectArray.count ?? 0
            for i in 0..<count{
                let selectView:LGTTaskTypeSelectView = weakSelf!.selectArray[i]
                var state:Bool = false
                if tag == i{
                    state = true
                }
                selectView.changeSelectState(select: state)
            }
            
            weakSelf?.conditionAlertVC.index = self.selectIndex
            weakSelf?.conditionAlertVC.view.addSubview((weakSelf?.navBar)!)
            weakSelf?.conditionAlertVC.conditionList = weakSelf?.taskConditionModel?.data?[tag]
            weakSelf?.conditionAlertVC.scrollToTop()
            if weakSelf?.conditionAlertVC.view.window == nil{
                weakSelf?.tabBarController?.present((weakSelf?.conditionAlertVC)!, animated: false, completion: nil)
            }
        }
    }
    
    override func setUI() {
        super.setUI()
        self.setBavBarStyle(navBarHiden: false, title: "", back: false)
        self.view.backgroundColor = ViewBackColor
        self.tableView = UITableView.init(frame: CGRect.init(x: 0.0, y: NavBarH(), width: Double(KScreenW), height: Double(KScreenH) - TabBarH() - NavBarH()), style: UITableView.Style.plain)
        self.view.addSubview(self.tableView!)
        self.tableView?.backgroundColor = ViewBackColor
        self.tableView?.separatorStyle = UITableViewCell.SeparatorStyle.none
        self.tableView?.delegate = self
        self.tableView?.dataSource = self
        self.tableView?.register(LGTHomeCell.classForCoder(), forCellReuseIdentifier: "cell")

        weak var weakSelf = self
        //ZHRefreshNormalHeader.headerWithRefreshing
        //ZHRefreshHeader.headerWithRefreshing
        self.tableView?.header = ZHRefreshNormalHeader.headerWithRefreshing(block: {
            weakSelf?.page = 1
            weakSelf?.tableView?.footer?.endRefreshing()
            weakSelf?.getData()
        })
        
        self.tableView?.footer = ZHRefreshBackNormalFooter.footerWithRefreshing(block: {
            weakSelf?.page += 1
            weakSelf?.tableView?.header?.endRefreshing()
            weakSelf?.getData()
        })
}

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.data.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:LGTHomeCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! LGTHomeCell
        cell.model = self.data[indexPath.row]
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let detailVC:LGTPostDetailVC = LGTPostDetailVC()
        detailVC.viewDetailType = DetailType.LLZ_Task_Detail_Type
        //detailVC.isPreview = false
        detailVC.taskModel = self.data[indexPath.row]
        //detailVC.isRWZ = false
        self.navigationController?.pushViewController(detailVC, animated: true)
    }
    
    func getTypeSelectView(title:String, tag:Int) -> LGTTaskTypeSelectButton{
        let selectView:LGTTaskTypeSelectButton = LGTViewCreateUtil.share.createTaskTypeSelectButton(position: LGTTaskTypeSelectButton.Position.right, spaceX:SizeFitFloat(5), title: title, image:"drop_down", selectImage:"retract", font: Font_Normal_15, color: TextColor, selectedColor: TextColor, dH:5)
        selectView.tag = tag
        selectView.addTarget(self, action: #selector(selectAction), for: UIControl.Event.touchUpInside)
        return selectView
    }
    
    @objc func selectAction(sender:LGTTaskTypeSelectButton){
        sender.isSelected = !sender.isSelected
    }
    
    func getTaskCondition(){
        weak var weakSelf = self
        LGTHttpUtil.httpUtil.requestData(url: LLZ_Task_Condition, param: [:], success: { (json) in
            let taskConditionModel:TaskConditionModel = try! lgtDecode(TaskConditionModel.self, param: (json))
            weakSelf?.taskConditionModel = taskConditionModel
            weakSelf?.initSelectView()
        }) { (json) in
            weakSelf?.showNoData(image: Net_NoData_Image, text: Net_Error_Text, subText: Net_Reload_Text, haveNav:false)
        }
    }
    
    func initSelectView(){
        let x0:Double = SizeFit(12)
        let count:Int = self.taskConditionModel?.data?.count ?? 0
        if count == 0 {
            return
        }
        
        let w:Double = SizeFit(100)
        let space:Double = (Double(KScreenW) - 2 * x0 - w * Double(count)) / Double(count - 1)
            //(Double(KScreenW) - 2 * x0 - space * Double(count - 1)) / Double(count)
        let typeArray:Array<LGTTaskTypeSelectView.Position> = [LGTTaskTypeSelectView.Position.Left, LGTTaskTypeSelectView.Position.Center, LGTTaskTypeSelectView.Position.Right]
        for i in 0..<count{
            let conditionListModel:ConditionListModel = self.taskConditionModel!.data![i]
            if i >= typeArray.count{
                break
            }
            let selectView:LGTTaskTypeSelectView = LGTTaskTypeSelectView.initWithPosition(positon: LGTTaskTypeSelectView.Position.Left, conditionListModel: conditionListModel, index: i)
            selectView.clickBlock = self.selectBlock
            selectView.tag = i
            self.selectArray.append(selectView)
            self.navBar.addSubview(selectView)
            selectView.snp.makeConstraints { (make) in
                make.left.equalTo(x0 + (w + space) * Double(i))
                make.height.equalTo(30)
                make.width.equalTo(w)
                make.bottom.equalTo(-5)
            }
        }
    }
    
    func getData(){
        weak var weakSelf = self
        var param:Dictionary<String, Any> = ["page": self.page]
        for i in 0..<self.selectArray.count{
            let selectView:LGTTaskTypeSelectView = self.selectArray[i]
            let currentConditionModel = selectView.currentConditionModel
            if currentConditionModel != nil{
                param[currentConditionModel!.key ?? "error"] = currentConditionModel!.value
            }
        }
        
        LGTHttpUtil.httpUtil.requestData(url: LLZ_Task_List_URL, param: param, showMessage: false, success: { (json) in
            weakSelf?.tableView?.header?.endRefreshing()
            weakSelf?.tableView?.footer?.endRefreshing()
            let data:Array<Dictionary<String, Any>> =  json["data"] as? Array<Dictionary<String, Any>> ?? Array.init()
            var modeArray:Array<TaskModel> = Array.init()
            for i in 0..<data.count{
                let param:Dictionary<String, Any> = data[i]
                let model:TaskModel = try! lgtDecode(TaskModel.self, param: param)
                modeArray.append(model)
            }
            
            if weakSelf?.page == 1{
                weakSelf?.data = modeArray
                
            }else{
                if weakSelf?.data == nil{
                    weakSelf?.data = Array.init()
                }
                weakSelf?.data.append(contentsOf: modeArray)
            }
            
            if weakSelf?.data.count == 0{
                weakSelf?.showNoData(image: NoData_Image, text: NoData_Text, subText: "")
            }else{
                weakSelf?.noView?.isHidden = true
            }
            
            if modeArray.count == 0{
                weakSelf?.tableView?.footer?.endRefreshingWithNoMoreData()
            }else{
                weakSelf?.tableView?.footer?.resetNoMoreData()
            }
            weakSelf?.tableView?.reloadData()
        }, failure: { (json) in
            weakSelf?.tableView?.header?.endRefreshing()
            weakSelf?.tableView?.footer?.endRefreshing()
        })
    }
    
    
    //LGTTaskConditionAlertDelegate
    func dismiss(_ vc: LGTTaskConditionAlertVC) {
        self.navBar.removeFromSuperview()
        self.view.addSubview(self.navBar)
    }
    
    //数据发生改变
    func selectIndex(_ index: Int, _ Row: Int) {
        
        self.selectIndex = -1
        let count:Int = self.selectArray.count
        for i in 0..<count{
            let selectView:LGTTaskTypeSelectView = self.selectArray[i]
            selectView.changeSelectState(select: false)
        }
        
        let selectView = self.selectArray[index]
        selectView.selelctRow(Row)
        //数据查询
        self.getData()
    }
}

 */
